/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * QuickStartJFrame.java
 *
 * Created on 2010-12-8, 18:36:28
 */
package org.lifxue.jqda.ui;

import java.awt.Dimension;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import javax.swing.JRootPane;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.lifxue.jqda.run.Command;
import org.lifxue.jqda.ui.autofield.AutoCompletionField;
import org.lifxue.jqda.ui.autofield.DefaultCompletionFilter;
import org.lifxue.jqda.data.DataUtil;
import org.lifxue.jqda.data.RecentData;
import org.lifxue.jqda.data.bean.AppInfoBean;
import org.lifxue.jqda.util.GlobalConstant;
import org.lifxue.jqda.util.GlobalVar;

/**
 *
 * @author lifxue
 */
public class QuickStartJFrame extends javax.swing.JFrame {

    private static Log logger = LogFactory.getLog(QuickStartJFrame.class);
    private static QuickStartJFrame qsJFrame;

    public static QuickStartJFrame getInstance() {
        synchronized (QuickStartJFrame.class) {
            if (qsJFrame == null) {
                qsJFrame = new QuickStartJFrame();
            }
        }
        return qsJFrame;
    }

    /**
     * Creates new form QuickStartJFrame
     */
    private QuickStartJFrame() {
        initComponents();

        //NONE                  无装饰（即去掉标题栏）
        //FRAME                 普通窗口风格
        //PLAIN_DIALOG          简单对话框风格
        //INFORMATION_DIALOG    信息对话框风格
        //ERROR_DIALOG          错误对话框风格
        //COLOR_CHOOSER_DIALOG 拾色器对话框风格
        //FILE_CHOOSER_DIALOG   文件选择对话框风格
        //QUESTION_DIALOG       问题对话框风格
        //WARNING_DIALOG        警告对话框风格
        this.getRootPane().setWindowDecorationStyle(JRootPane.NONE);//采用指定的窗口装饰风格

        //定位窗口在屏幕的位置
        if (GlobalVar.CONFIG == null || GlobalVar.CONFIG.isEmpty()) {
            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            Dimension frameSize = getSize();
            setLocation(new Point((screenSize.width - frameSize.width) / 2,
                    (screenSize.height - frameSize.height) / 2));
        } else {
            Point point = DataUtil.getPointFromHashMap();
            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            Dimension frameSize = getSize();
            setLocation(point);
        }
        //设置底色
        this.getContentPane().setBackground(new java.awt.Color(204, 204, 255));

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        autoTextField = new org.lifxue.jqda.ui.autofield.AutoCompletionField();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setUndecorated(true);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowDeactivated(java.awt.event.WindowEvent evt) {
                formWindowDeactivated(evt);
            }
        });

        init();
        autoTextField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                autoTextFieldKeyPressed(evt);
            }
        });

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/lifxue/jqda/ui/butterfly32.png"))); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(autoTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 431, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel1)
                .addContainerGap(14, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(autoTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 34, Short.MAX_VALUE)
                    .addComponent(jLabel1))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void autoTextFieldKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_autoTextFieldKeyPressed
        // TODO add your handling code here:
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            String str = autoTextField.getText();
            if (Command.run(str)) {
                this.setVisible(false);
            }
        }

    }//GEN-LAST:event_autoTextFieldKeyPressed

    private void formWindowDeactivated(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowDeactivated
        // TODO add your handling code here:
        //frame失去焦点时，窗口隐藏
        this.setVisible(false);
    }//GEN-LAST:event_formWindowDeactivated

    private void init() {
        this.addMouseListener(moveWindowListener);
        this.addMouseMotionListener(moveWindowListener);
        updateData();

    }

    public void updateData() {
        List<String> tempvector = getDate();
        ((AutoCompletionField) autoTextField).setFilter(new DefaultCompletionFilter(tempvector));

    }
    //窗口的拖拽移动
    private MouseAdapter moveWindowListener = new MouseAdapter() {

        private Point lastPoint = null;

        @Override
        public void mousePressed(MouseEvent e) {
            lastPoint = e.getLocationOnScreen();
        }

        @Override
        public void mouseDragged(MouseEvent e) {
            Point point = e.getLocationOnScreen();
            int offsetX = point.x - lastPoint.x;
            int offsetY = point.y - lastPoint.y;
            Rectangle bounds = QuickStartJFrame.this.getBounds();
            bounds.x += offsetX;
            bounds.y += offsetY;
            QuickStartJFrame.this.setBounds(bounds);
            lastPoint = point;
            //logger.debug(point.x +":"+point.y);
            GlobalVar.CONFIG.put(GlobalConstant.CONFIG_FILE_X, String.valueOf(QuickStartJFrame.this.getBounds().x));
            GlobalVar.CONFIG.put(GlobalConstant.CONFIG_FILE_Y, String.valueOf(QuickStartJFrame.this.getBounds().y));
            //logger.debug("x="+GlobalVar.CONFIG_HM.get(GlobalConstant.CONFIG_FILE_X);
            //logger.debug("y="+GlobalVar.CONFIG_HM.get(GlobalConstant.CONFIG_FILE_Y);
        }
    };

    /**
     * 得到数据
     *
     * @return
     */
    public List<String> getDate() {
        List<AppInfoBean> list = new ArrayList<AppInfoBean>();
        Iterator i = GlobalVar.APPLICATIONS.entrySet().iterator();
        while (i.hasNext()) {
            java.util.Map.Entry entry = (java.util.Map.Entry) i.next();
            String key = (String) entry.getKey(); //返回与此项对应的键
            List<AppInfoBean> pathlist = (List<AppInfoBean>) entry.getValue(); //返回与此项对应的值
            for (AppInfoBean value : pathlist) {
                AppInfoBean tempApp = new AppInfoBean();
                tempApp.setVolumeOfUse(value.getVolumeOfUse());
                tempApp.setPath(key + GlobalConstant.QSFRAME_DELIMITER + value.getPath());
                list.add(tempApp);
            }

        }
        
        List<AppInfoBean> templist = RecentData.getRecentData();
        if ( templist != null) {
            list.addAll(templist);
        }


        //Collections.sort(list);//排序
        Collections.sort(list, Collections.reverseOrder());//倒序
        List<String> temp = new ArrayList<String>();
        for (int inx = 0; inx < list.size(); inx++) {
            temp.add(list.get(inx).getPath());
        }

        return temp;
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new QuickStartJFrame().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField autoTextField;
    private javax.swing.JLabel jLabel1;
    // End of variables declaration//GEN-END:variables
}
